package com.woohua.security.config;

import com.woohua.security.handler.AuthLimitHandler;
import com.woohua.security.handler.LoginSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

/***
 * @title WebSecurityConfig
 * @description
 * @author baiji
 * @version 1.0.0
 * @create 2023/11/23 13:25
 **/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, jsr250Enabled = true)
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // 关闭csrf 前后端未分离，并且使用thymeleaf模板，可以注释此配置
                .csrf().disable()

                // 配置登录页面
                .formLogin(formLogin -> formLogin
                        .loginPage("/login").permitAll()
                        // 配置登录成功后的默认页面
                        //.defaultSuccessUrl("/home")
                        // 配置登录成功后的操作
                        .successHandler(new LoginSuccessHandler())
                )
                // 记住密码
                //.rememberMe(Customizer.withDefaults())
                // 用户权限不足处理器
                .exceptionHandling(exceptionHandling -> exceptionHandling.accessDeniedHandler(new AuthLimitHandler()))
                // 登出授权
                .logout().permitAll();
        // 授权配置
        http.authorizeRequests()
                /* 所有静态文件可以访问 */
                .antMatchers("/js/**", "/css/**", "/images/**").permitAll()
                /* 所有 以/ad 开头的 广告页面可以访问 */
                .antMatchers("/ad/**").permitAll()
                .anyRequest().fullyAuthenticated();
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        // 返回自定义的 UserDetailsService 实现类，用于获取用户信息
        return new UserDetailServiceImpl();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
